import 'package:analyzer/dart/element/element.dart' as ele;
import 'package:source_gen/source_gen.dart';
import 'package:build/build.dart';
import 'dart:io';
import 'jenkinsfile.dart';
import 'tpl/tpl.dart' as tpl;

class JenkinsfileGenerator extends GeneratorForAnnotation<GJenkinsfile> {
  final separator = Platform.pathSeparator;

  @override
  generateForAnnotatedElement(
      ele.Element element, ConstantReader annotation, BuildStep buildStep) {
    // logPrint('start jenkinsfile', level: Level.info);
    var enable = false;
    var annoMap = {
      "token": "",
      "webHook": "",
      "gitUrl": "",
      "branch": "",
      "mergeTarget": "",
      "androidMsg": "",
      "iOSMsg": "",
    };
    try {
      enable = annotation.read('enable').boolValue;
    } catch (e) {}
    if (!enable) return null;

    var androidArgs = [];
    var iOSArgs = [];
    var shellSymbol = [];
    try {
      androidArgs = annotation
          .read('androidArgs')
          .listValue
          .map((e) => e.toStringValue())
          .toList();
    } catch (e) {}
    try {
      iOSArgs = annotation
          .read('iOSArgs')
          .listValue
          .map((e) => e.toStringValue())
          .toList();
    } catch (e) {}
    try {
      shellSymbol = annotation
          .read('shellSymbol')
          .listValue
          .map((e) => e.toStringValue())
          .toList();
    } catch (e) {}

    bool isOk = true;
    try {
      annoMap.forEach((key, value) {
        annoMap[key] = annotation.read(key).stringValue;
        if (annoMap[key] == null) {
          isOk = false;
        }
      });
    } catch (e) {}
    if (!isOk) return null;

    String code = tpl.clazzTpl(
      token: annoMap["token"],
      webHook: annoMap["webHook"],
      gitUrl: annoMap["gitUrl"],
      shellSymbol: shellSymbol.join(" && "),
      branch: annoMap["branch"],
      mergeTarget: annoMap["mergeTarget"],
      androidMsg: annoMap["androidMsg"],
      iOSMsg: annoMap["iOSMsg"],
      androidArgs: androidArgs.join(" "),
      iOSArgs: iOSArgs.join(" "),
    );
    File("${Directory.current.path}${separator}Jenkinsfile")
      ..createSync(recursive: true)
      ..writeAsStringSync(code, flush: true);

    return null;
  }
}

Builder jenkinsfileBuilder(BuilderOptions options) =>
    LibraryBuilder(JenkinsfileGenerator(),
        generatedExtension: ".jenkinsfile.dart");
